package org.charles.zhifou.common.aop;

import jakarta.annotation.Resource;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.charles.zhifou.common.annotation.AuthCheck;
import org.charles.zhifou.common.response.ResponseCodeEnum;
import org.charles.zhifou.enums.UserRoleEnum;
import org.charles.zhifou.common.exception.BusinessException;
import org.charles.zhifou.common.exception.ThrowUtils;
import org.charles.zhifou.model.entity.User;
import org.charles.zhifou.service.UserService;
import org.springframework.stereotype.Component;

/**
 * <h1>权限校验 AOP</h1>
 *
 * @author charles
 * @version 1.0
 */
@Aspect
@Component
public class AuthInterceptor {

    @Resource
    private UserService userService;

    /**
     * 权限校验与拦截
     *
     * @param authCheck
     * @return
     */
    @Before("@annotation(authCheck)")
    public void doInterceptor(AuthCheck authCheck) {
        // 获取方法所需权限
        UserRoleEnum neededRoleEnum = authCheck.neededRole();

        // 获取当前登录用户已有权限
        User loginUser = userService.getLoginUser();
        UserRoleEnum userRoleEnum = loginUser.getUserRole();

        // 当前方法不需要权限, 放行
        if (neededRoleEnum == null) {
            return;
        }

        // 如果当前用户不具备任何权限, 拒绝
        ThrowUtils.throwIf(userRoleEnum == null, ResponseCodeEnum.NO_AUTH_ERROR);

        // 如果被封号, 拒绝
        ThrowUtils.throwIf(UserRoleEnum.BAN.equals(userRoleEnum), ResponseCodeEnum.NO_AUTH_ERROR);

        // 如果必须有管理员权限, 而当前用户没有, 拒绝
        if (UserRoleEnum.ADMIN.equals(neededRoleEnum) && !UserRoleEnum.ADMIN.equals(userRoleEnum)) {
            throw new BusinessException(ResponseCodeEnum.NO_AUTH_ERROR);
        }
    }
}

